package com.zb.redis;

import com.zb.constant.RedisConstant;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.TimeUnit;

/**
 * @Author WEN
 * @Date 2023/7/28 0028
 **/
@Component
public class RedisUtil {
    private RedisTemplate<String, Object> redisTemplate;

    public static RedisUtil redisUtil;

    public RedisUtil(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @PostConstruct
    public void init() {
        redisUtil = this;
        redisUtil.redisTemplate = this.redisTemplate;
    }


    /**
     * 缓存数据
     * @param k
     * @param data
     */
    public static void setCache(String k, Object data) {
        setCache(k, data, RedisConstant.DEFAULT_EXPIRE_TIME);
    }

    /**
     * 缓存数据
     * @param k
     * @param data 数据
     * @param time 过期时间，单位：秒
     */
    public static void setCache(String k, Object data, long time) {
        redisUtil.redisTemplate.opsForValue().set(k, data,  time, TimeUnit.SECONDS);
    }

    /**
     * 判断key是否存在
     * @param k
     * @return
     */
    public static boolean hasKey(String k) {
        return Boolean.TRUE.equals(redisUtil.redisTemplate.hasKey(k));
    }

    /**
     * 根据Key获取缓存
     * @param k
     * @return
     */
    public static Object getByKey(String k) {
        return redisUtil.redisTemplate.opsForValue().get(k);
    }

    /**
     * 清除缓存
     * @param k
     */
    public static void clearCache(String k) {
        redisUtil.redisTemplate.delete(k);
    }

}
